package mk.edu.ii.navigatemacedonia;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;


import android.app.Activity;

import android.content.Intent;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class ResultsView extends Activity {
	public static final String USER_PREFERENCE="my_preferences";
	ArrayList<Site> sites = new ArrayList<Site>();
	Site [] sites_array;	
	String []sites_list ;
	TextView addressTextView ;
	Location myLocation = new Location(LocationManager.GPS_PROVIDER);
	Spinner spinner ;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.resultview);
        Intent intent = getIntent();
          
        
        spinner = (Spinner)findViewById(R.id.second_Spinner01);
        addressTextView = (TextView)findViewById(R.id.second_Addres);
        sites = (ArrayList<Site>)intent.getSerializableExtra("sites");
                
        myLocation.setLatitude(intent.getDoubleExtra("latitude",0d));
        myLocation.setLongitude(intent.getDoubleExtra("longitude", 0d));
        
        addressTextView.setText(ReverseGeoCoding(myLocation.getLatitude(), myLocation.getLongitude()));
        
        populateLocationList((ListView)findViewById(R.id.sitesListView),(int)spinner.getScrollBarStyle());
        populateSpinner(spinner);
        ListView listView = (ListView)findViewById(R.id.sitesListView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        		
        		Intent siteInfoView = new Intent(view.getContext(),SiteInfoActivity.class);
        		
        		siteInfoView.putExtra("site", sites.get((int)id));
        		siteInfoView.putExtra("longitude", myLocation.getLongitude());
        		siteInfoView.putExtra("latitude", myLocation.getLatitude());
    			startActivity(siteInfoView);
    			
        	}
        });
        
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        	public void onItemSelected( AdapterView<?> parent, View view, int position, long id){
        		populateLocationList((ListView)findViewById(R.id.sitesListView), (int)spinner.getSelectedItemPosition());
        	}
        	public void onNothingSelected(AdapterView<?> parent){
        		
        	}
        });
	}
	
	public void populateLocationList(ListView locationListView, int sort_by){
			
		for(int i=0;i<sites.size();i++){
    		Location dest = new Location(LocationManager.GPS_PROVIDER);
    		dest.setLatitude(sites.get(i).getSiteLatitude());
    		dest.setLongitude(sites.get(i).getSiteLongitude());
    		Float distance=myLocation.distanceTo(dest);
    		sites.get(i).setSiteDistance(distance);
    		myLocation.bearingTo(dest);
    		sites.get(i).setSiteBearing(myLocation.bearingTo(dest));
    	}
		if(sort_by==0){
			Collections.sort(sites,new DistComp());
		}
		else{
			Collections.sort(sites,new RatingComp());
		}
        SiteAdapter siteAdapter = new SiteAdapter(this, R.layout.siteitem, sites);
        
        //Bind the array adapter to the listview.
        locationListView.setAdapter(siteAdapter);
        
        //seting the choice mode to SingleChoiceMode=1
        locationListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
     }
	
	private void populateSpinner(Spinner spinner) {
    	// Populate the update frequency spinner
    	ArrayAdapter<CharSequence> aAdapter;
    	aAdapter = ArrayAdapter.createFromResource(this,R.array.sort,android.R.layout.simple_spinner_item);
    	aAdapter.setDropDownViewResource(
    			android.R.layout.simple_spinner_dropdown_item);
    	spinner.setAdapter(aAdapter);
    	spinner.setSelection(0);
    	
    }
	
	private String ReverseGeoCoding(Double latitude,Double longitude)
    {
    	Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
   	    
    	try {
    		List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
    		StringBuilder sb = new StringBuilder();
   			if (addresses.size() > 0) {
   				Address address = addresses.get(0);
   				for(int i=0;i<3;i++)
   					if(address.getAddressLine(i)!=null)
   						sb.append(address.getAddressLine(i)+", ");
   					else
   						sb.append("");
   				return sb.toString();
   			} 
   			else {
   				return "No location information found";
   			}
   	    }
        catch (Exception e) {return "No location information found";} 
    }
	
	class DistComp implements Comparator{

		public int compare(Object object1, Object object2) {
			// TODO Auto-generated method stub
			Float site1 = ((Site)object1).getSiteDistanceF();
			Float site2 = ((Site)object2).getSiteDistanceF();
			return site1.compareTo(site2);
		}
		
	}
	
	class RatingComp implements Comparator{

		public int compare(Object object1, Object object2) {
			// TODO Auto-generated method stub
			Float site1 = ((Site)object1).getSiteRating();
			Float site2 = ((Site)object2).getSiteRating();
			return site2.compareTo(site1);
		}
		
	}
	
	
}
